#!/bin/bash

UPDATEURL="https://musicdb.hifiberry.com"
HOST=`cat /etc/uuid`
MODE=REBOOT
FORCE=0
DEVMODE=0

# find correct version
. /etc/hifiberry.state
if [ "$PIVERSION" == "" ]; then
 PIVERSION=`cat /etc/raspberrypi.version`
fi

# Map 0 to 0w
if [ "$PIVERSION" == "0" ]; then
 PIVERSION=0w
fi

#
# There are different release tags available:
#
# critical:     this update needs to be installed
# stable:       lastest stable release
# latest:       latest official release, might include features 
#               that are not yet in the stable release
# experimental: development release, not recommended for normal
#               users, might break things

if [ -f /custom/updater.release ]; then
 RELEASE=`cat /custom/updater.release`
elif [ -f /etc/updater.release ]; then
 RELEASE=`cat /etc/updater.release`
else
 RELEASE=critical
fi

for i in "$@"; do
 case $i in
    --reboot)
    	MODE=REBOOT
    	;;
    --simulate)
    	MODE=SIMULATE
    	;;
    --check)
    	MODE=CHECK
    	;;
    --force)
    	FORCE=1
    	;;
    --latest)
    	RELEASE=latest
    	;;
    --experimental)
    	RELEASE=experimental
    	;;
    --stable)
    	RELEASE=stable
	;;
    --critical)
        RELEASE=critical
        ;;
    *)
	RELEASE=$1
 esac
done

# Check version
MYVERSION=`cat /etc/hifiberry.version 2>/dev/null`
if [ "$MYVERSION" == "" ]; then
 MYVERSION=0
fi
VERSION=`curl -f -s -d host=$HOST -d version=$MYVERSION -d piversion=$PIVERSION -d releasetag=$RELEASE -d zipsupport=1 -d card="$CURRENT_CARD" -d hatinfo="$CURRENT_HATINFO" -m 10 $UPDATEURL/update-system`
if [ "$?" != 0 ]; then
 echo "Couldn't get release information from $UPDATEURL/update-system, aborting..."
 sleep 60
 exit 1
fi

sleep 5

if [ "$VERSION" == "" ]; then
 VERSION=$MYVERSION
fi

if [ "$VERSION" -le "$MYVERSION" ]; then
 if [ "$MODE" == "CHECK" ]; then
   exit 0
 fi
 if [ "$FORCE" != "1" ]; then
   echo "you are already using the latest version ($MYVERSION vs. $VERSION)"
   exit 0
 fi
fi

if [ "$MODE" == "CHECK" ]; then
 echo "$VERSION"
 echo
 curl  $UPDATEURL/releasenotes/$VERSION
 exit
fi
 
echo "updating from $MYVERSION to $VERSION..."

# find correct version
UPDATER=`curl -f -s $UPDATEURL/updater-url/$VERSION/$PIVERSION/zip`
if [ "$UPDATER" == "" ]; then
 echo "No updater found for $VERSION/$PIVERSION"
 exit 1
fi

# download it
echo "downloading $UPDATER..."
cd /data
if [[ $UPDATER == *tar.gz ]]; then
 curl -f $UPDATER --progress-bar -o updater.tar.gz 
else
 curl -f $UPDATER --progress-bar -o updater.zip
fi 

if [ "$?" != "0" ]; then
 echo "Could not download updater $UPDATER, aborting"
 exit 1
fi

# extract update
if [ "$MODE" == "REBOOT" ]; then
 /opt/hifiberry/bin/extract-update --reboot
elif [ "$MODE" == "SIMULATE" ]; then
 /opt/hifiberry/bin/extract-update --simulate
fi 
